package com.financing.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.financing.model.Data;
import com.jfinal.kit.PathKit;

public class Http {

	public static String post(String url) throws Exception{  
		return Http.post(url,Data.put("1","1"));
	}
	
	public static String post(String url,Map<Object,Object> map) throws Exception{  
    	/**String responseString="";
    	PostMethod xmlpost;
 	    int statusCode = 0;
 	    HttpClient httpclient = new HttpClient();
 	    httpclient.setConnectionTimeout(new Integer(200000).intValue());
 	    xmlpost = new PostMethod(url);
 	    httpclient.getParams().setParameter(
 	    		HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        try{
        	//组合请求参数
        	List<NameValuePair> list=new ArrayList<NameValuePair>();
        	for(Object key : map.keySet()) {
				NameValuePair nvp=new NameValuePair(String.valueOf(key),String.valueOf(map.get(key)));
				list.add(nvp);
        	}
			NameValuePair[] nvps=new NameValuePair[list.size()];
        	xmlpost.setRequestBody(list.toArray(nvps)); 
        	statusCode = httpclient.executeMethod(xmlpost);
	    	responseString = xmlpost.getResponseBodyAsString();
            if(statusCode<HttpURLConnection.HTTP_OK || statusCode>=HttpURLConnection.HTTP_MULT_CHOICE){
                System.err.println("失败返回码[" + statusCode + "]"); 
                throw new Exception("请求接口失败，失败码[ "+ statusCode +" ]");
            }
        }catch(IOException e){
            e.printStackTrace();
            System.err.println(e.toString());
            throw e;
        }
        return responseString;*/
		String  result = null; 
		CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        httpClient = HttpClients.createDefault();
        // 把一个普通参数和文件上传给下面这个地址 是一个servlet
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder me = MultipartEntityBuilder.create();
        StringBody blankStr = new StringBody("", ContentType.create("text/plain", Consts.UTF_8));
    	for(Object key : map.keySet()) {	   
    		String k = String.valueOf(key);
    		if(k.contains("file")) {
    			String v = (String)map.get(k);
    	        // 把文件转换成流对象FileBody
    	        me.addPart(k,Str.nb(v)?new FileBody(new File(PathKit.getWebRootPath()+v)):blankStr);
    		}else {
    			me.addPart(k,new StringBody(String.valueOf(map.get(key)), ContentType.create("text/plain", Consts.UTF_8)));
    		}
    	}
        httpPost.setEntity(me.build());
        // 发起请求 并返回请求的响应
        response = httpClient.execute(httpPost);
        // 获取响应对象
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            result = EntityUtils.toString(resEntity, Charset.forName("UTF-8"));
        }
        // 销毁
        EntityUtils.consume(resEntity);
		return result;
    } 
	
	public static JSONObject post(String url,JSONObject json){  
		org.apache.http.client.HttpClient httpClient = HttpClientBuilder.create().build();
		JSONObject res = null;  
		try {
		    HttpPost request = new HttpPost(url);
		    StringEntity params =new StringEntity(json.toJSONString());
		    request.addHeader("content-type", "application/x-www-form-urlencoded");
		    request.setEntity(params);
		    HttpResponse response = httpClient.execute(request);
            if(response.getStatusLine().getStatusCode()==200){  
                HttpEntity entity = response.getEntity();  
                ContentType charset = ContentType.getOrDefault(entity);
                BufferedReader streamReader = new BufferedReader(new InputStreamReader(entity.getContent(),charset.getCharset())); 
                StringBuilder responseStrBuilder = new StringBuilder();

                String inputStr;
                while ((inputStr = streamReader.readLine()) != null){
                    responseStrBuilder.append(inputStr);
                }
                res = JSON.parseObject(responseStrBuilder.toString());
            }  
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return res;
    } 
}
